package com.cli.spring_session_demo.controller;

import com.cli.spring_session_demo.common.ReturnData;
import com.cli.spring_session_demo.common.StatusCode;
import com.cli.spring_session_demo.exceptions.MyException;
import com.cli.spring_session_demo.model.User;
import com.cli.spring_session_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author xiongmin
 * @Description //TODO
 * @Date 2020/3/25 15:00
 * @Version 1.0
 **/
@RestController
@RequestMapping(value = "/user")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/login")
    public ReturnData login(HttpServletRequest request, String account, String password) throws MyException {
        User user = userService.findUserByAccountAndPassword(account, password);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("loginUserId", user.getId());
            redisTemplate.opsForValue().set("loginUser:" + user.getId(), session.getId());

            return new ReturnData(StatusCode.REQUEST_SUCCESS, user, "登录成功！");
        } else {
            throw new MyException("账户名或密码错误！");
        }
    }

    @RequestMapping(value = "/getUserInfo")
    public ReturnData get(long userId) throws MyException {
        User user = userService.findUserByUserId(userId);
        if (user != null) {
            return new ReturnData(StatusCode.REQUEST_SUCCESS, user, "查询成功！");
        } else {
            throw new MyException("用户不存在！");
        }
    }

    @RequestMapping(value = "/register")
    public ReturnData register(User user) throws MyException {
        userService.save(user);
        if (user.getId() != null) {
            return new ReturnData(StatusCode.REQUEST_SUCCESS, user, "注册成功！");
        } else {
            throw new MyException("注册失败！");
        }
    }
}
